import logging
from datetime import datetime

from django.shortcuts import render
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView

from orders.models import Order
from payments.models import PaymentRecord
from payments.wxpay import WxPayClient
from utils.snowflake import generate_id

logger = logging.getLogger('django')


def parse_time(time_str):
    """处理微信支付返回的时间字符串"""
    if not time_str:
        return None
    # 将ISO格式时间字符串转换为datetime对象
    try:
        # 处理带时区的时间字符串，去除时区信息
        time_str = time_str.split('+')[0].replace('T', ' ')
        return datetime.strptime(time_str, '%Y-%m-%d %H:%M:%S')
    except Exception as e:
        logger.error(f"时间解析异常：{str(e)}")
        return None


# Create your views here.

class WxPayOrderApiView(APIView):
    permission_classes = [IsAuthenticated]

    def post(self, request):
        """
        微信下单,对接微信Native下单接口
        """
        # 接受参数
        order_number = request.data.get('order_number')
        # 校验参
        if not order_number:
            return Response({"code": 0, "message": "订单编号不能为空"})

        try:
            # 获取订单
            order = Order.objects.get(order_number=order_number, user=request.user)
            # 校验订单状态
            if order.order_status != 0:
                return Response({"code": 0, "message": "订单状态有误"})

            # 生成支付订单号
            pay_order_number = str(generate_id())

            # 创建支付记录
            payment_record = PaymentRecord.objects.create(
                order=order,
                order_number=order_number,
                pay_order_number=pay_order_number,
                pay_method=2,
                pay_amount=order.real_price,
                pay_status=0,

            )

            # 调用微信支付
            client = WxPayClient()
            total_fee = int(float(order.real_price) * 100)  # 单位是分
            description = f"码境空间课程订单:{order_number}"
            code_url = client.create_order(pay_order_number, total_fee, description)
            if not code_url:
                return Response({"code": 0, "message": "微信下单失败"})
                # 更新支付记录
            payment_record.pay_remark = "发起微信支付成功"
            payment_record.save()
            # 更新订单:订单支付方式
            order.pay_method = 2
            order.save()

            # 构建返回结果
            result = {
                'pay_order_number': pay_order_number,
                'pay_url': code_url,
                'total_fee': total_fee,
                'order_number': order_number,
            }

            return Response({"code": 1, "message": "微信下单成功", "data": result})

        except Exception as e:
            logger.error(f"微信下单异常：{str(e)}")
            return Response({"code": 0, "message": str(e)})


class WxPayQueryAPIView(APIView):
    permission_classes = [IsAuthenticated]

    def get(self, request):
        """
        微信支付订单查询
        """
        # 接受参数
        order_number = request.query_params.get('order_number')
        pay_order_number = request.query_params.get('pay_order_number')
        # 校验参数
        if not order_number:
            return Response({"code": 0, "message": "订单号不能为空"})

        try:
            order = Order.objects.get(order_number=order_number, user=request.user)
            if order.order_status == 1:
                return Response({"code": 1, "message": "订单已支付", "order_number": order_number})

            # 查询支付记录
            try:
                payment_record = PaymentRecord.objects.get(order_number=order_number, pay_order_number=pay_order_number,
                                                           pay_method=2)
            except PaymentRecord.DoesNotExist:
                return Response({"code": 0, "message": "支付记录不存在", 'order_number': order_number})

            client = WxPayClient()
            result = client.query_order(pay_order_number)
            trade_state = result.get("trade_state")
            success_time = parse_time(result.get("success_time"))
            transaction_id = result.get("transaction_id")
            logger.info(f"微信支付查询结果:{result}")
            logger.info(f"微信支付查询结果:{trade_state},{success_time},{transaction_id}")
            if trade_state == "SUCCESS":

                logger.info(f"订单{order_number}支付成功")
                # 更新订单状态
                order.order_status = 1
                order.pay_time = success_time
                order.trade_no = transaction_id
                order.save()

                payment_record.pay_status = 1
                payment_record.pay_time = success_time
                payment_record.trade_no = transaction_id
                payment_record.pay_remark = "微信支付成功"
                payment_record.save()

                return Response({
                    "code": 1,
                    "message": "订单支付成功",
                    "order_number": order_number
                })

            else:
                logger.info(f"订单{order_number}支付失败")
                return Response({
                    "code": 0,
                    "message": "订单支付失败",
                    "order_number": order_number
                })
        except Exception as e:
            logger.error(f"微信支付查询异常：{str(e)}")
            return Response({"code": 0, "message": f"查询支付状态失败:{str(e)}"})
